// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成
package com.fowo.api.documentCirculation.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fowo.api.common.meta.MetaDataObject;
import com.fowo.api.common.meta.MetaDataObjects;
import com.fowo.api.common.model.IdListPo;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.R;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.documentCirculation.model.DataTaskImportPo;
import com.fowo.api.documentCirculation.model.DataTaskItemVo;
import com.fowo.api.documentCirculation.model.DataTaskSearchParamPo;
import com.fowo.api.documentCirculation.model.DataTaskVo;
import com.fowo.api.documentCirculation.service.DataTaskService;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.user.model.JwtUserInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StreamUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 单据流转 - 数据事务控制器
 * @author yl_ls
 */
@Tag(name = "单据流转 - 数据事务")
@RequestMapping("/api/document-circulation/data-task")
@RestController
public class DataTaskController {

  @Resource
  private DataTaskService service;

  @Operation(summary = "读取对象数据")
  @GetMapping("meta-data")
  public R<List<MetaDataObject>> getMetaData() {
    return R.data(MetaDataObjects::getObjects);
  }


  @Operation(summary = "获取与表名对应的源配置头，用于是否显示下推按钮")
  @GetMapping("from-table/{fromTable}")
  public R<List<DataTaskItemVo>> getMainByFromTable(@PathVariable String fromTable, @RequestParam(value = "objectName", required = false) String objectName) {
    return R.data(() -> service.getMainByFromTable(fromTable, objectName));
  }

  @Operation(summary = "获取与表名对应的目标配置头，用于是否显示勾稽按钮")
  @GetMapping("to-table/{toTable}")
  public R<List<DataTaskItemVo>> getMainByToTable(@PathVariable String toTable, @RequestParam(value = "objectName", required = false) String objectName) {
    return R.data(() -> service.getMainByToTable(toTable, objectName));
  }


  @Operation(summary = "查询结果")
  @GetMapping
  public R<List<DataTaskItemVo>> search(DataTaskSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    search.setCurrentUserId(jwtUserInfo.getUserId());
    return R.data(service.search(search));
  }

  @Operation(summary = "查询最后更新时间")
  @GetMapping("lastUpdateTime")
  public R<Date> searchLastUpdateTime(DataTaskSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    search.setCurrentUserId(jwtUserInfo.getUserId());
    return R.data(service.searchLastUpdateTime(search));
  }

  @Operation(summary = "获取分页查询结果")
  @GetMapping("page")
  public R<Page<DataTaskItemVo>> getPage(DataTaskSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    search.setCurrentUserId(jwtUserInfo.getUserId());
    return R.data(service.pageSearch(search));
  }

  @Operation(summary = "获取详情")
  @GetMapping("{id}")
  public R<DataTaskVo> getVoById(@PathVariable Long id) {
    return R.data(() -> service.getVoById(id));
  }

  @Operation(summary = "获取编号相关的名称列表")
  @GetMapping("name/{ids}")
  public R<List<String>> getVoById(@PathVariable String ids) {
    List<Long> idList = Arrays
      .asList(ids.split(","))
      .stream()
      .map(Long::valueOf)
      .collect(Collectors.toList());
    return R.data(() -> service.getNameByIds(idList));
  }

  @PreAuthorize("@am.canAccess('dataTaskCreate')")
  @Operation(summary = "新增")
  @PostMapping
  public R<Long> create(@Validated @RequestBody DataTaskVo model) {
    return R.data(() -> service.create(model));
  }

  @PreAuthorize("@am.canAccess('dataTaskEdit')")
  @Operation(summary = "更新")
  @PutMapping
  public R update(@RequestBody DataTaskVo model) {
    return R.run(() -> service.update(model));
  }

  @PreAuthorize("@am.canAccess('dataTaskEdit')")
  @Operation(summary = "编辑更新")
  @PutMapping("edit")
  public R updateForEdit(@RequestBody DataTaskVo model) {
    return R.run(() -> service.updateForEdit(model));
  }

  @PreAuthorize("@am.canAccess('dataTaskDelete')")
  @Operation(summary = "删除")
  @DeleteMapping("{id}")
  public R delete(@PathVariable Long id) {
    return R.run(() -> service.delete(id));
  }

  @PreAuthorize("@am.canAccess('dataTaskDelete')")
  @Operation(summary = "批量删除")
  @DeleteMapping("batch")
  public R batchDelete(@RequestBody IdListPo po) {
    return R.run(() -> service.batchDelete(po.getIds()));
  }

  @PreAuthorize("@am.canAccess('dataTaskCreate')")
  @Operation(summary = "导入预览")
  @PostMapping("import-preview")
  public R<List<ImportRow<DataTaskImportPo>>> importPreview(
    @RequestBody SysFile sysFile
  ) {
    return R.data(() -> service.importPreview(sysFile));
  }

  @PreAuthorize("@am.canAccess('dataTaskCreate')")
  @Operation(summary = "完成导入")
  @PostMapping("import-done")
  public R importDone(@RequestBody List<ImportRow<DataTaskImportPo>> rows) {
    return R.run(() -> service.importDone(rows));
  }

  @Operation(summary = "下载导入模版")
  @GetMapping("import/template")
  public void downloadImportTemplate(HttpServletResponse response)
    throws IOException {
    ResponseUtils.setAttachmentFileName(response, "数据事务导入模版.xlsx");
    InputStream inputStream = new ClassPathResource("templates/DataTask.xlsx")
      .getInputStream();
    StreamUtils.copy(inputStream, response.getOutputStream());
  }

  @Operation(summary = "导出")
  @GetMapping("export")
  public void export(
    DataTaskSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    search.setCurrentUserId(jwtUserInfo.getUserId());
    service.export(search, response);
  }
}
